class CommentatorTests extends GroovyTestCase {

  def post
  def comment

  protected void setUp() {
    post = new Post(title: "First Grails Project",
        teaser: "Clearing out the clutter",
        content: "The full content of the article",
        published: false).save()                                          
    comment = new Comment(post: post, comment: "my comment")
  }

  void testCommentatorIsSavedWhenCommentIsSaved() {

    def comment = new Comment(comment: "my comment",
        dateCreated: new Date(),
        post: post,
        who: new Commentator(name: "Jon"))

    if (comment.save()) {
      def savedComment = Comment.get(comment.id)
      assertEquals("Jon", savedComment.who.name);
    } else {
      comment.errors.allErrors.each {
        assertEquals("", it.defaultMessage)
      }
    }
  }

  void testSettingDeepProperties() {
    def params = [comment: 'my comment', "who.name": "Jon", post: post, dateCreated: new Date()]

    def comment = new Comment(params)
    assertEquals("my comment", comment.comment)
    assertEquals("Jon", comment.who.name)

    if (!comment.save()) {
      assertFalse("saving the comment failed", true)
    }


    assertNotNull(comment.who)
    assertNotNull(comment.who.id)
    def commentator = Commentator.get(comment.who.id)
    assertEquals("Jon", commentator.name)
    assertNotNull(comment.id)

  }

  void testIfSpecifiedTheCommentatorsEmailAndUrlMustBeWellFormed() {
    def commentator = new Commentator(
        name: "fred",
        email: "badmail",
        url: "badurl")

    comment.who = commentator

    assertNull(comment.save())

    commentator.email = "fred@foo.com"
    assertNull(comment.save())

    commentator.url = "http://fred.foo.com"
    assertNotNull(comment.save())
  }
}
